package cn.edu.nuc.creditSystem.service.credit.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.nuc.creditSystem.bean.credit.Account;
import cn.edu.nuc.creditSystem.bean.credit.Capital;
import cn.edu.nuc.creditSystem.dao.BaseMapper;
import cn.edu.nuc.creditSystem.dao.credit.inf.AccountMapper;
import cn.edu.nuc.creditSystem.dao.credit.inf.CapitalMapper;
import cn.edu.nuc.creditSystem.dao.credit.inf.MemberMapper;
import cn.edu.nuc.creditSystem.service.BaseImpl;
import cn.edu.nuc.creditSystem.service.credit.service.CapitalService;
import cn.edu.nuc.creditSystem.utils.AnalogInterface;
import cn.edu.nuc.creditSystem.utils.Arith;
@Service
public class CapitalImpl extends BaseImpl<Capital> implements AnalogInterface,CapitalService{
	@Autowired
	private CapitalMapper cm;
	@Autowired
	private AccountMapper am;
	@Autowired
	private MemberMapper mm;
	@Override
	public BaseMapper<Capital> getBaseDao() {
		return cm;
	}
	@Override
	@Transactional
	public Boolean transferAccount(Integer from, Integer to, Double money,String reason,int i){
		Account a=am.get(from);
		Account b=am.get(to);
		a.setMoney(Arith.add(a.getMoney(),-money));
		if(i==2)a.setLend(Arith.add(a.getLend(),money));
		am.update(a);
		b.setMemberId(viladateMember(b.getFlow(),money));
		b.setMoney(Arith.add(b.getMoney(),money));
		b.setFlow(Arith.add(b.getFlow(),money));
		if(i==1)b.setEarpprofit(Arith.add(b.getEarpprofit(),money));
		if(i==3)b.setLoan(Arith.add(b.getLoan(),money));
		am.update(b);
		Capital c=new Capital();
		c.setOuter(from);
		c.setInflow(to);
		c.setReason(reason);
		c.setType(5);
		if(i==2 || i==3){c.setType(1);}
		if(i==1)c.setType(3);
		c.setMoney(money);
		cm.insert(c);
		return true;
	}

	@Override
	@Transactional
	public Boolean recharge(Integer to, Double money,String reason) {
		Account a=am.get(to);
		a.setMemberId(viladateMember(a.getFlow(),money));
		a.setMoney(Arith.add(a.getMoney(),money));
		a.setFlow(Arith.add(a.getFlow(),money));
		am.update(a);
		Capital c=new Capital();
		c.setInflow(to);
		c.setReason(reason);
		c.setType(2);
		c.setMoney(money);
		cm.insert(c);
		return true;
	}

	@Override
	public Boolean withdrawals(Integer from, Double money) {
		Account a=am.get(from);
		a.setMoney(Arith.add(a.getMoney(),money));
		am.update(a);
		Capital c=new Capital();
		c.setOuter(from);
		c.setReason("提现"+money+"元！");
		c.setType(4);
		c.setMoney(-money);
		cm.insert(c);
		return true;
	}
	/**
	 * 判断会员等级是否提升
	 * @param memberId
	 * @param now
	 * @param add
	 * @return
	 */
	private  int viladateMember(Double now,Double add){
		now=now==null?0.0:now;
		Double b=Arith.add(now, add);
		Integer nowMemberId=mm.getNowMemberIdByMoney(b);
		return nowMemberId;
	}
}
